﻿using Blog1._0.Data;
using Blog1._0.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using Until;
using System.Data.Entity.SqlServer.Utilities;

namespace Blog1._0.Service
{
    /// <summary>
    /// 【角色管理】逻辑层
    /// </summary>
    public class Admin_RoleService : Repository
    {
        /// <summary>
        /// 角色管理查询
        /// </summary>
        /// <param name="filter"></param>
        /// <param name="pageInfo"></param>
        /// <returns></returns>
        public LayuiResult GetListByFilter(RoleModel filter, PageInfo pageInfo)
        {
            var db = this.Base().BeginTrans();
            var roles = db.FindList<Guo_Role>();
            var query = from i in roles
                        orderby i.CreateOn descending
                        select new
                        {
                            Id = i.Id,
                            LoginID = i.LoginID,
                            UserName = i.UserName,
                            Remark = i.Remark,
                            Status = i.Status,
                            CreateOn = i.CreateOn,
                            UpdateOn = i.UpdateOn,
                            CreateBy = i.CreateBy,
                            UpdateBy = i.UpdateBy
                        };

            //操作名称
            if (!string.IsNullOrEmpty(filter.RoleName))
            {
                string actionName = filter.RoleName.ToString();
                query = query.Where(t => t.UserName.Contains(actionName));
            }

            //状态
            if (filter.IsActive != null)
            {
                bool isActive = Convert.ToBoolean(filter.IsActive);
                query = query.Where(t => t.Status == isActive);
            }

            var data = query.Skip((pageInfo.page - 1) * pageInfo.limit).Take(pageInfo.limit);//分页
            return new LayuiResult { code = 0, count = roles.Count(), data = query.ToList() };
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool CreateModel(RoleModel model)
        {
            var db = this.Base();
            Guo_Role diay = new Guo_Role();
            db.SaveChanges();
            diay.UserName = model.RoleName;
            diay.LoginID = model.RoleCode;
            diay.Remark = model.Remark;
            diay.Status = model.IsActive;
            diay.CreateBy = Current.GetEntity().OperatorId;
            diay.CreateOn = model.CreateOn;

            db.Insert<Guo_Role>(diay);
            //提交失败，则检查实体类是否加上自增ID标识
            return db.Commit() > 0 ? true : false;
        }

        /// <summary>
        /// 详情
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public IEnumerable<RoleModel> ReadModel(int Id)
        {
            var db = this.Base();
            var data = db.IQueryable<Guo_Role>().Where(t => t.Id == Id);
            var query = from i in data
                        select new RoleModel()
                        {
                            Id = i.Id,
                            RoleName = i.UserName,
                            RoleCode = i.LoginID,
                            IsActive = i.Status,
                            CreateOn = i.CreateOn,
                            UpdateOn = i.UpdateOn,
                            CreateBy = i.CreateBy,
                            UpdateBy = i.UpdateBy,
                            Remark = i.Remark,
                        };

            return query.ToList();
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool UpdateList(RoleModel model)
        {
            var db = this.Base();
            var res = db.IQueryable<Guo_Role>(t => t.Id == model.Id).FirstOrDefault();
            res.UserName = model.RoleName;
            res.LoginID = model.RoleCode;
            res.Remark = model.Remark;
            res.Status = model.IsActive;
            res.UpdateOn = model.UpdateOn;
            res.UpdateBy = model.UpdateBy;
            db.Update(res);
            return db.Commit() > 0 ? true : false;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public bool DeleteModel(int Id)
        {
            var db = this.Base();
            try
            {
                //删除角色时,同时删除菜单角色权限记录
                db.Delete<Guo_Role>(t => t.Id == Id);
                db.Delete<Guo_Admin_Role_Menu>(t => t.RoleId == Id);
                return db.Commit() > 0 ? true : false;
            }
            catch (Exception)
            {
                // db.Rollback();
                throw new Exception("删除失败！");
            }
        }

        /// <summary>
        /// 权限分配 数据加载
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public IEnumerable<MenuModel> GetAvailableMenuList(int roleId)
        {
            var db = this.Base();
            var menu = db.FindList<Guo_Admin_Role_Menu>().OrderBy(t => t.MenuId);
            var res = db.FindList<Guo_AdminMenu>();
            ActionService actionService = new ActionService();

            var query = (from i in menu
                         join t in res
                         on i.MenuId equals t.ID
                         group i by new
                         {
                             t.ID,
                             t.MenuName,
                             t.MenuIcon,
                             t.OrderNo,
                             t.ParentId
                         } into g orderby g.Key.ID 
                         select new MenuModel()
                         {
                             Id = g.Key.ID,
                             MenuName = g.Key.MenuName,
                             MenuIcon = g.Key.MenuIcon,
                             OrderNo = g.Key.OrderNo,
                             ParentId = g.Key.ParentId
                         }).ToList();

            foreach (var item in query)
            {
                item.MenuActionHtml = actionService.GetActionListHtmlByRoleId(roleId, item.Id);
                item.IsChecked = actionService.GetListByRoleIdMenuId(roleId, item.Id).Count() > 0 ? true : false;
            }
            return query;
        }

        /// <summary>
        /// 保存权限修改
        /// </summary>
        /// <param name="roled"></param>
        /// <returns></returns>
        public bool GetInsertBash(IEnumerable<MenuRoleActionModel> entitys, int roled)
        {
            var db = this.Base();
            var res = db.FindList<Guo_Admin_Role_Menu>();
            var data = from i in res where i.RoleId == roled select i;
            foreach (var del in data)
            {
                db.Delete(del);
            }
            db.SaveChanges();

            Guo_Admin_Role_Menu menu = new Guo_Admin_Role_Menu();
            if (entitys != null)
            {
                var datas = entitys.ToList();
                foreach (var item in datas)
                {
                    menu.MenuId = item.MenuId;
                    menu.RoleId = item.RoleId;
                    menu.ActionId = item.ActionId;
                    db.Insert(menu);
                    db.SaveChanges();
                }
            }

            db.Commit();
            return menu != null ? true : false;          
        }
    }
}
